<template>
  <div class="paging" v-if="result.length">
    <button @click="index--" :disabled="index == 1">上一页</button>
    <span>{{`第${index}页/共${num}页`}}</span>
    <button @click="index++" :disabled="index == num">下一页</button>
  </div>
</template>

<script>
export default {
  name: 'Paging',

  props: {
    // 需要分页的数据集
    result:{
      type: Array,
      default: () => []
    },
    // 每页的个数
    count: {
      type: Number,default: 10
    }
  },

  data() {
    return {
      index: 1
    };
  },

  computed: {
    // 最大页数
    num(){
      return Math.ceil(this.result.length/this.count)
    }
  },

  watch: {
    result(){
      this.index = 1
      this.init()
    },
    index: 'init'
  },

  methods: {
    // 初始化
    init(){
      this.$emit('result',this.result.slice((this.index-1) * this.count, this.index * this.count))
    }
  }
};
</script>

<style scoped>
.paging{
  margin-top: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.paging span{
  font-size: 0.8rem;
}
.paging .active{
  background-color: green;
  color: white;
}
.paging button{
  height: 22px;
  border: 1px solid gray;
  cursor: pointer;
  padding: 0 4px;
  margin: 0 4px;
}
</style>